
import {
	apiBaseURL
} from './config.js';

// 异步请求
function request(url, method, data, header = {}) {
	// 自动将accessToken添加到request的header中
	header['X-Access-Token'] = uni.getStorageSync('token')?uni.getStorageSync('token'):'';

	return new Promise((resolve, reject) => {
		uni.request({
			url: apiBaseURL + url,
			data: data,
			header: header,
			method: method,
			success: (res) => {
				if (res.data.code == 200) { // 成功
					resolve(res.data);
				} else if (res.data.code == 401) { // access_token无效
					uni.clearStorageSync();
					uni.reLaunch({
						url: '/pages/login/login'
					})
				} else  { // 失败
					reject(res);
					uni.showToast({
						title: res.data.message,
						icon: 'none',
					});
				} 
			},
			fail: (error) => {
				if (error.statusCode !== 200) {
					showError(error.statusCode)
					return
				}
			},
			complete: () => {
				setTimeout(function () {
					uni.hideLoading();
				}, 1500);
			}
		})
	})
}

//get
export const get = (url, data) => {
	return request(url, 'get',data, {
		'content-type': 'application/json'
	});
}

//post
export const post = (url, data) => {
	return request(url, 'post',data, {
		'content-type': 'application/x-www-form-urlencoded'
	});
}

//postJson
export const postJson = (url, data) => {
	return request(url, 'post', data, {
		'content-type': 'application/json'
	});
}

const showError = code => {
	let errorMsg = ''
	switch (code) {
		case 400:
			errorMsg = '请求参数错误'
			break
		case 401:
			errorMsg = '未授权，请登录'
			break
		case 403:
			errorMsg = '跨域拒绝访问'
			break
		case 404:
			errorMsg = `请求地址出错: ${apiBaseURL}`
			break
		case 408:
			errorMsg = '请求超时'
			break
		case 500:
			errorMsg = '服务器内部错误'
			break
		case 501:
			errorMsg = '服务未实现'
			break
		case 502:
			errorMsg = '网关错误'
			break
		case 503:
			errorMsg = '服务不可用'
			break
		case 504:
			errorMsg = '网关超时'
			break
		case 505:
			errorMsg = 'HTTP版本不受支持'
			break
		default:
			errorMsg = '请求失败'
			break
	}

	uni.showToast({
		title: errorMsg,
		icon: 'none',
		complete: function () {
			setTimeout(function () {
				uni.hideToast();
			}, 1500);
		}
	});
}
